package com.minio.project.Service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.minio.project.Entity.Img;
import com.minio.project.Service.ImgService;
import com.minio.project.Mapper.ImgMapper;
import com.minio.project.Utils.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.Map;
import java.util.Objects;

/**
 * @author ASUS
 * @description 针对表【product_img】的数据库操作Service实现
 * @createDate 2025-04-18 15:00:26
 */
@Service
public class ImgServiceImpl extends ServiceImpl<ImgMapper, Img> implements ImgService {

    @Autowired
    private MinioUtil minioUtil;

    /**
     * 上传图片
     * 1.实体转换
     * 2.写数据库
     *
     * @param file
     * @return
     */
    @Override
    public String uploadImage(MultipartFile file) {
        Img entity = new Img();
        if (file.isEmpty()) {
            throw new RuntimeException("上传文件不能为空");
        }
        try {
            Map<String, Object> map = minioUtil.upload(file);
            String key = (String) map.get("key");
            String url = (String) map.get("url");

            entity.setId(1L);
            entity.setUrl(url);
            entity.setImgKey(key);
            entity.setImgName(file.getName());
            entity.setCreateTime(new Date());
            entity.setUploadUser("admin");
            save(entity);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 删除图片
     *
     * @param name
     * @return
     */
    @Override
    public void deleteImage(String name) {
        QueryWrapper<Img> wrapper = new QueryWrapper<>();
        wrapper.eq("name", name);
        Img entity = getOne(wrapper);
        if (Objects.isNull(entity)) {
            throw new RuntimeException("图片不存在");
        }
        boolean success = minioUtil.deleteFile(entity.getImgKey());
        if (!success) {
            throw new RuntimeException("Minio删除图片失败");
        }
        int row = baseMapper.delete(wrapper);
        if (row == 0) {
            throw new RuntimeException("图片删除失败");
        }
    }
}




